﻿using System.Xml;
using digiTwitter.Core;

namespace digiTwitter
{
    public class Friendship
    {
        public const string FRIENDSHIP_CREATE_URL = "http://twitter.com/friendships/create/{0}.xml";
        public const string FRIENDSHIP_DESTROY_URL = "http://twitter.com/friendships/destroy/{0}.xml";
        public const string FRIENDSHIP_EXISTS_URL = "http://twitter.com/friendships/exist.xml?user_a={0}&user_b={1}";

        /// <summary>
        /// Allows the authenticating users to follow the user specified in the ID parameter.
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="follow"></param>
        /// <returns></returns>
        public TwitterUser Create(string userName, bool follow)
        {
            string url = string.Format(FRIENDSHIP_CREATE_URL, userName);

            if (follow)
                url += "?follow=true";

            XmlDocument doc =  HTTPRequester.RequestPOSTResponse(url, string.Empty);

            return new TwitterUser(doc);
        }

        /// <summary>
        /// Allows the authenticating users to unfollow the user specified in the ID parameter.
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public TwitterUser Destroy(string userName)
        {
            string url = string.Format(FRIENDSHIP_DESTROY_URL, userName);

            XmlDocument doc = HTTPRequester.RequestPOSTResponse(url, string.Empty);

            return new TwitterUser(doc);        
        }

        /// <summary>
        /// Tests for the existance of friendship between two users. 
        /// </summary>
        /// <returns>Will return true if user_a follows user_b, otherwise will return false.</returns>
        public bool Exists(string userA, string userB)
        {
            if (string.IsNullOrEmpty(userA) || string.IsNullOrEmpty(userB))
                throw new TwitterException("User A or B cannot be empty");

            string url = string.Format(FRIENDSHIP_EXISTS_URL, userA,userB);

            var doc = new XmlDocument();
            doc.LoadXml(HTTPRequester.GetResponseString(url));

            return bool.Parse(doc.SelectSingleNode("friends").InnerText);
        }
    }
}
